<template>
  <!-- 对话框表单 -->
  <el-dialog
    class="ba-operate-dialog"
    :close-on-click-modal="false"
    :model-value="baTable.form.operate ? true : false"
    @close="baTable.toggleForm"
  >
    <template #header>
      <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']">
        {{ baTable.form.operate !== "edit" ? "添加" : "编辑" }}
      </div>
    </template>
    <el-scrollbar
      v-loading="baTable.form.loading"
      class="ba-table-form-scrollbar"
    >
      <div
        class="ba-operate-form"
        :class="'ba-' + baTable.form.operate + '-form'"
        :style="'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'"
      >
        <el-form
          ref="formRef"
          @keyup.enter="baTable.onSubmit(formRef)"
          :model="baTable.form.items"
          label-position="right"
          :label-width="baTable.form.labelWidth + 'px'"
          :rules="rules"
          v-if="!baTable.form.loading"
        >
          <el-form-item label="角色名称" prop="nickName">
            <el-input v-model="baTable.form.items!.roleName" />
          </el-form-item>
          <el-form-item label="权限字符" prop="roleKey">
            <el-input v-model="baTable.form.items!.roleKey" />
            <div class="block-help">
              控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)
            </div>
          </el-form-item>
          <el-form-item label="角色顺序" prop="roleSort">
            <el-input-number
              v-model="baTable.form.items!.roleSort"
              controls-position="right"
              :min="0"
            />
          </el-form-item>
          <FormItem
            label="状态"
            v-model="baTable.form.items!.status"
            type="radio"
            :data="{
              content: { 0: '正常', 1: '停用' },
              childrenAttr: { border: true },
            }"
          />
          <el-form-item prop="auth" label="菜单权限">
            <el-tree
              ref="treeRef"
              :default-checked-keys="
                baTable.form.operate == 'edit' ? menus : []
              "
              show-checkbox
              :default-expand-all="true"
              node-key="id"
              empty-text="加载中，请稍候"
              :props="{
                children: 'children',
                label: 'label',
                value: 'id',
                class: treeNodeClass,
              }"
              :data="state.menuRules"
            />
          </el-form-item>
        </el-form>
      </div>
    </el-scrollbar>
    <template #footer>
      <div
        :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'"
      >
        <el-button @click="baTable.toggleForm('')">取消</el-button>
        <el-button
          v-blur
          :loading="baTable.form.submitLoading"
          @click="baTable.onSubmit(formRef)"
          type="primary"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import type { TableRow } from "@/utils/baTable"; //表格列行类型
import { reactive, ref, inject, onMounted, watch, nextTick } from "vue";
import type baTableClass from "@/utils/baTable";
import type { ElForm, FormItemRule, FormRules, ElTree } from "element-plus";
import FormItem from "@/components/formItem/index.vue";
import { useRole } from "@/store/backend/SysM/role";
import type Node from "element-plus/es/components/tree/src/model/node";

const treeRef = ref<InstanceType<typeof ElTree>>();

interface MenuRules {
  id: number;
  title: string;
  children: MenuRules[];
}
interface Props {
  menus: anyObj[];
}
const role = useRole();
//接受来自父组件的注入
const baTable = inject("baTable") as baTableClass;
const formRef = ref<InstanceType<typeof ElForm>>();
const props = withDefaults(defineProps<Props>(), {
  menus: () => [],
});

const rules = reactive<FormRules>({
  roleName: [{ required: true, message: "角色名称不能为空", trigger: "blur" }],
  roleKey: [{ required: true, message: "权限字符不能为空", trigger: "blur" }],
  roleSort: [{ required: true, message: "角色顺序不能为空", trigger: "blur" }],
  auth: [
    {
      validator: (rule: any, val: string, callback: Function) => {
        let ids = getCheckeds();
        if (ids.length <= 0) {
          return callback(new Error("请选择权限"));
        }
        return callback();
      },
    },
  ],
});

// // 所有部门节点数据
// const getDeptAllCheckedKeys = () => {
//   // 目前被选中的部门节点
//   let checkedKeys = treeRef.value!.getCheckedKeys();
//   // 半选中的部门节点
//   let halfCheckedKeys = treeRef.value!.getHalfCheckedKeys();
//   checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
//   return checkedKeys;
// };
const getCheckeds = () => {
  return treeRef
    .value!.getCheckedKeys()
    .concat(treeRef.value!.getHalfCheckedKeys());
};
const state: {
  defaultCheckedKeys: number[];
  menuRules: MenuRules[];
} = reactive({
  defaultCheckedKeys: [],
  menuRules: [],
});
const treeNodeClass = (data: anyObj, node: Node) => {
  if (node.isLeaf) return "";
  let addClass = true;
  for (const key in node.childNodes) {
    if (!node.childNodes[key].isLeaf) {
      addClass = false;
    }
  }
  return addClass ? "penultimate-node" : "";
};
onMounted(() => {
  role.getMenuRoleTreeList().then((res: any) => {
    state.menuRules = res.data;
  });
});

watch(
  () => baTable.form.operate,
  (newValue, oldValue) => {
    console.log("newValue", newValue);
    if (newValue === "add") {
      nextTick(() => {
        treeRef.value!.setCheckedKeys([], false);
      });
    }
  },
  {
    immediate: true, // 值如果是true会打开首次监听
  }
);
defineExpose({
  getCheckeds,
});
</script>
<style lang="scss" scoped>
.el-scrollbar {
  overflow: auto;
  position: relative;
  height: 100%;

  .el-scrollbar__wrap {
    overflow: auto;
    height: 100%;
  }
}
:deep(.penultimate-node) {
  .el-tree-node__children {
    padding-left: 60px;
    white-space: pre-wrap;
    line-height: 12px;
    .el-tree-node {
      display: inline-block;
    }
    .el-tree-node__content {
      padding-left: 5px !important;
      padding-right: 5px;
      .el-tree-node__expand-icon {
        display: none;
      }
    }
  }
}
</style>
